package me.eg.third;

import me.eg.util.ListNode;

/**
 * 23. 合并K个升序链表
 * <p>
 * 给你一个链表数组，每个链表都已经按升序排列。
 * <p>
 * 请你将所有链表合并到一个升序链表中，返回合并后的链表。
 * <p>
 * https://leetcode-cn.com/problems/merge-k-sorted-lists/
 */
public class MergeKLists {
    private ListNode[] list;

    public ListNode mergeKLists(ListNode[] lists) {
        if (lists == null || lists.length == 0) return null;
        if (lists.length == 1) return lists[0];
        this.list = lists;
        return divide(0, this.list.length - 1);
    }

    private ListNode divide(int start, int end) {
        if (start == end) return list[start];

        int mid = (start + end) / 2;
        ListNode first = divide(start, mid);
        ListNode second = divide(mid + 1, end);
        return merge(first, second);
    }

    private ListNode merge(ListNode first, ListNode second) {
        ListNode head = new ListNode();
        ListNode cur = head;
        while (first != null || second != null) {
            if (first == null || (second != null && first.val > second.val)) {
                cur.next = second;
                second = second.next;
            } else {
                cur.next = first;
                first = first.next;
            }
            cur = cur.next;
        }
        return head.next;
    }
}
